package com.crc.luojian.method;

import com.crc.luojian.annotation.Controller;
import com.crc.luojian.annotation.RequestMapping;
import com.crc.luojian.beans.model.ApplicationContext;
import com.crc.luojian.util.ApplicationContextUtils;
import com.crc.luojian.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @program: luojian-springframework
 * @description: 存储请求url 和 MethodHandler
 * @author: luojian58
 * @create: 2021-06-10 17:51
 */
public class MethodHandlerMappering {
    private Map<String,MethodHandler> methodHandlerMap = new HashMap<>();

    /**
     * @Author luojian
     * @Description 初始化controller requestMapping 将请求路径和处理方法放入map 中
     * @Date  2021/6/10 18:19
     * @Param []
     * @return void
     **/
    public void init(){
        Set<Class<?>> controllerSets = ReflectionUtils.getAllClass(Controller.class);
        if(!controllerSets.isEmpty()){
            for(Class<?> controllerClazz : controllerSets){
                RequestMapping annotation = controllerClazz.getAnnotation(RequestMapping.class);
                //获取Controller 类上的RequestMapping 路径
                String parentPath = annotation == null? "":annotation.value();
                if(annotation != null){
                    Method[] methods = controllerClazz.getMethods();
                    if(methods != null && methods.length>1){
                        for (Method method : methods){
                            RequestMapping declaredAnnotation = method.getDeclaredAnnotation(RequestMapping.class);
                            if(declaredAnnotation != null) {
                                String path = parentPath + declaredAnnotation.value();
                                MethodHandler methodHandler =
                                        new MethodHandler(ApplicationContextUtils.getContext().getBean(controllerClazz), method);
                                methodHandlerMap.put(path, methodHandler);
                            }
                        }
                    }
                }
            }
        }
    }

    public MethodHandler getByUrl(String url) {
        return methodHandlerMap.get(url);
    }
}
